
<?php

  //数据库操作文件

  //数据库链接函数封装
  function db_connect($db_name,$host='127.0.0.1',$db_user='root',$db_pwd='root',$charset='utf8'){

    $link = mysqli_connect($host,$db_user,$db_pwd,$db_name);

    // 判断数据库是否连接成功
    if(!$link){
      echo"<script>alert('数据库连接失败');history.go(-1)</script>";die;
    }

    // 设置数据库传输编码
    mysqli_query($link, 'set names '.$charset);

    return $link;


  }

  // 删除语句函数封装
  function del($table,$where=array(),$status=false){
    // print_r($where);die;

    if(is_array($where)){
      $str = implode(',',$where);
      $where = "in ($str)";
    }else{
      if(!$status){
        $where = " id = ".$where;
      }

    }
     $sql = "delete from `$table` where $where ";

    mysqli_query($GLOBALS['link'],$sql);

    return mysqli_affected_rows($GLOBALS['link']);

  }

  //修改语句函数封装
  function edit($table,$where,$data){

    $field = '';
    foreach ($data as $k => $v) {
      $field.="`$k` = '$v',";
    }
    $field = substr($field,0,-1);//把循环后的最后一个逗号去掉



    $sql = " update `$table` set $field where `id`=$where";

    mysqli_query($GLOBALS['link'],$sql);

    return mysqli_affected_rows($GLOBALS['link']);

  }

  // 添加语句函数封装
  function add($table,$where=array()){

    $key = "`".implode("`,`",array_keys($where))."`";//组装字段名

    $v = "'".implode("','",array_values($where))."'";//组装值

    $sql = "insert into `$table` ($key)values($v)";

    mysqli_query($GLOBALS['link'],$sql);

    return mysqli_affected_rows($GLOBALS['link']);
  }


  // 查询语句函数封装
  function getSelectByOne($table,$where,$field='*'){

    if(is_array($where)){
      $str = '';
      $i = 0;
      foreach ($where as $k => $v) {
        // 如果循环到最后一次则不拼接
        if($i==count($where)-1){
          $str.="`$k` = '$v'";
        }else{
          $str.="`$k` = '$v' and ";
        }
        $i++;
      }
      $where = $str;
    }

    $sql = "select $field from `$table` where $where limit 1";

    $result = mysqli_query($GLOBALS['link'],$sql);

    return mysqli_fetch_assoc($result);
  }

  // 多条查询函数封装
  function getSelect($table,$where=1,$order='',$limit='',$field='*'){

    $where1 = '';
    if(!empty($order)){
      $where1.=" order by ".$order;
    }
    if(!empty($limit)){
      $where1.=" limit $limit ";
    }

    $sql = "select $field from `$table` where $where $where1";
    $result = mysqli_query($GLOBALS['link'],$sql);

    while ($arr = mysqli_fetch_assoc($result)){
      $data[]=$arr;

    }

    return $data;
  }